// const { array } = require('joi')
const db = require('../config/db')

/**
 * 用户列表接口逻辑
 */
exports.userList = (req, res) => {
    // 获取前端的参数
    let {Search, page, size} = req.query
    
    page = (page - 1) * size
    let pageSql = 'select * from cms_user where del=0 '
     // 查询用户总数的sql
    let totalSql = 'select count(*) as total from cms_user where del=0 '
    // 查询用户列表sql
    if(Search == null){
        pageSql = pageSql + 'limit ?, ?'
        argument = [Number(page), Number(size)]
    }else {
        pageSql = pageSql + ' and loginname like ? limit ?, ?'
        totalSql = totalSql + ' and loginname like ?'
        argument = ["%" + Search + "%",Number(page), Number(size)]
    }    
    
    db.query(pageSql,argument,(err, resPage) => {
        
        if(err) {
            return res.send({ code: 1, message: err.message});
        }
        db.query(totalSql, "%" + Search+ "%",(err,resTotal) => {
            if(err) {
                return res.send({ code: 1, message: err.message});
            }
            res.send({
                code: 0,
                data:{
                    list: resPage,
                    total: resTotal
                }
            })
        })
    })
}

/**
 * 修改用户接口
 */
exports.updateUserListById = (req, res) => {
    let {id, loginname, username,} = req.query;
    let sql = 'update cms_user set  loginname = ?, username = ? where id = ?'
    db.query(sql, [ loginname, username, id], (err, results) => {
        if(err) {
            return res.send({ code: 1, message: err.message});
        }
        res.send({ code: 0, message:'修改成功'});
    })  
}

// 删除用户接口
exports.deleteUserListById = (req, res) => {
    let {id} = req.query;
    let sql = 'update cms_user set del = 1 where id = ?'
    db.query(sql, id, (err, result) => {
        if(err) {
            return res.send({ code: 1, message: err.message});
        }
        res.send({ code: 0, message:'删除成功'})

    })
}